package com.ly.hotel.broadcast;

import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.service.SPAService;
import com.ly.hotel.util.HttpHelper;
import com.ly.hotel.util.HttpRequestFailException;

import de.greenrobot.event.EventBus;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ShutdownReceiver extends BroadcastReceiver {  
    @Override  
    public void onReceive(final Context context, Intent intent) {  
        Log.e("shutdown", "系统正在关机中...");  
        SharedPreferencesConfig.setSpaBootFlag(context, true);
        Log.i("shutdown", "设置关机标志为"+SharedPreferencesConfig.getSpaBootFlag(context));  
		//把服务灯和后台的呼叫也取消掉
		new Thread() {
			@Override
			public void run() {
		        ((MyApplication) context.getApplicationContext()).setLight(false);
		        SPAService.getCalling(MyApplication.getMAC(), Constants.CALL_CANCLE);
		        
				String url = MyApplication.getHost() + SPAService.PROJECT + "/api/cancelcall.json?mac=" + MyApplication.getMAC();
				
				Log.i("shutdown", url);
				try {
					String result = HttpHelper.getStringSync(null, url);
					Log.i("shutdown", "取消呼叫:" + result);  
				} catch (HttpRequestFailException e) {
					Log.e("shutdown", "失败");  
					e.printStackTrace();
				}
					
		        Log.e("shutdown", "关闭服务灯和取消所有呼叫");  
			}
		}.start();
		
        EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_SYSTEM_SHUTDOWN 
        		+ "\t" + MyApplication.getApkVersion() 
        		+ "\t" + Constants.API_VERSION 
        		+ "\t" + Constants.LYAGENT_VERSION
        		+ "\t" + MyApplication.serverVersion));
    } 
}  